package ui;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import model.AttributeDefinition;
import model.Customer;
import service.AttributeService;
import service.CustomerService;
import utils.CommonUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户编辑页面
 */
public class EditCustomerPage extends Application {
    
    private Customer customer;
    private CustomerService customerService = new CustomerService();
    private Map<Integer, Control> attributeControls = new HashMap<>(); // 存储属性ID与控件的映射
    private Map<Integer, CheckBox> highlightControls = new HashMap<>(); // 存储属性ID与高亮复选框的映射
    
    public EditCustomerPage(Customer customer) {
        this.customer = customer;
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("编辑客户 - " + customer.getCustomerName());
        
        VBox mainContainer = new VBox();
        mainContainer.setPadding(new Insets(20));
        mainContainer.setSpacing(15);
        mainContainer.getStyleClass().add("form-container");
        
        // 标题
        Label titleLabel = new Label("编辑客户信息");
        titleLabel.getStyleClass().add("form-title");
        
        // 客户名称输入框
        GridPane formGrid = new GridPane();
        formGrid.setHgap(15);
        formGrid.setVgap(15);
        formGrid.getStyleClass().add("form-grid");
        
        Label nameLabel = new Label("客户名称:");
        TextField nameField = new TextField(customer.getCustomerName());
        nameField.setPrefWidth(300);
        
        formGrid.add(nameLabel, 0, 0);
        formGrid.add(nameField, 1, 0);
        
        // 添加客户名称的高亮复选框标签
        Label highlightLabel = new Label("高亮显示:");
        formGrid.add(highlightLabel, 2, 0);
        
        // 获取客户的属性值
        Map<Integer, String> attributeValues = customer.getAttributeValues();
        int rowIndex = 1;
        
        // 只显示客户拥有的属性
        for (Map.Entry<Integer, String> entry : attributeValues.entrySet()) {
            int attributeId = entry.getKey();
            String value = entry.getValue();
            
            // 通过attributeId获取属性定义
            AttributeDefinition attr = AttributeService.getAttributeById(attributeId);
            if (attr != null) {
                String displayName = attr.getDisplayName();
                int dataType = attr.getDataType().getValue();
                
                Label attrLabel = new Label(displayName + ":");
                Control inputControl;
                
                // 根据数据类型创建不同的输入控件
                switch (dataType) {
                    case 1: // STRING
                        TextField textField = new TextField(value);
                        inputControl = textField;
                        break;
                    case 2: // INTEGER
                        TextField intField = new TextField(value);
                        intField.textProperty().addListener((observable, oldValue, newValue) -> {
                            if (!newValue.matches("\\d*")) {
                                intField.setText(newValue.replaceAll("[^\\d]", ""));
                            }
                        });
                        inputControl = intField;
                        break;
                    case 3: // DECIMAL
                        TextField decimalField = new TextField(value);
                        decimalField.textProperty().addListener((observable, oldValue, newValue) -> {
                            if (!newValue.matches("\\d*(\\.\\d*)?")) {
                                decimalField.setText(oldValue);
                            }
                        });
                        inputControl = decimalField;
                        break;
                    case 4: // BOOLEAN
                        ComboBox<String> boolCombo = new ComboBox<>(FXCollections.observableArrayList("是", "否"));
                        boolCombo.setValue("是".equals(value) ? "是" : "否");
                        inputControl = boolCombo;
                        break;
                    case 5: // DATE
                    case 6: // DATETIME
                    case 7: // TIMESTAMP
                        DatePicker datePicker = new DatePicker();
                        // 可以添加日期解析逻辑
                        inputControl = datePicker;
                        break;
                    default:
                        TextField defaultField = new TextField(value);
                        inputControl = defaultField;
                        break;
                }
                
                // 添加标签和控件到表单
                formGrid.add(attrLabel, 0, rowIndex);
                formGrid.add(inputControl, 1, rowIndex);
                
                // 添加高亮复选框
                CheckBox highlightCheckBox = new CheckBox();
                highlightCheckBox.setSelected(customer.isAttributeHighlighted(attributeId));
                formGrid.add(highlightCheckBox, 2, rowIndex);
                
                // 存储属性ID与控件的映射关系
                attributeControls.put(attributeId, inputControl);
                highlightControls.put(attributeId, highlightCheckBox);
                
                rowIndex++;
            }
        }
        
        // 按钮区域
        HBox buttonBox = new HBox();
        buttonBox.setSpacing(15);
        buttonBox.setAlignment(Pos.CENTER_RIGHT);
        
        Button cancelButton = new Button("取消");
        cancelButton.setStyle("-fx-background-color: #5a67d8; -fx-text-fill: white; -fx-font-size: 16px; -fx-padding: 10 20;");
        cancelButton.getStyleClass().add("button");
        cancelButton.setOnAction(e -> {
            // 返回客户详情页
            CustomerDetailPage detailPage = new CustomerDetailPage(customer);
            try {
                detailPage.start(new Stage());
                primaryStage.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });
        
        Button saveButton = new Button("保存");
        saveButton.setStyle("-fx-background-color: #5a67d8; -fx-text-fill: white; -fx-font-size: 16px; -fx-padding: 10 20;");
        saveButton.getStyleClass().add("button");
        saveButton.setOnAction(e -> {
            // 更新客户名称
            customer.setCustomerName(nameField.getText());
            
            // 更新属性值和高亮状态
            for (Map.Entry<Integer, Control> entry : attributeControls.entrySet()) {
                int attributeId = entry.getKey();
                Control control = entry.getValue();
                String value = "";
                
                if (control instanceof TextField) {
                    value = ((TextField) control).getText();
                } else if (control instanceof ComboBox) {
                    value = ((ComboBox<String>) control).getValue();
                } else if (control instanceof DatePicker) {
                    if (((DatePicker) control).getValue() != null) {
                        value = ((DatePicker) control).getValue().toString();
                    }
                }
                
                // 更新属性值
                customer.setAttributeValue(attributeId, value);
                
                // 更新高亮状态
                CheckBox highlightCheckBox = highlightControls.get(attributeId);
                if (highlightCheckBox != null) {
                    customer.setAttributeHighlight(attributeId, highlightCheckBox.isSelected());
                }
            }
            
            // 保存到数据库
            boolean success = customerService.updateCustomer(customer);
            
            if (success) {
                CommonUtil.showAlert("成功", "客户信息更新成功！", Alert.AlertType.INFORMATION);
                
                // 返回客户详情页
                CustomerDetailPage detailPage = new CustomerDetailPage(customer);
                try {
                    detailPage.start(new Stage());
                    primaryStage.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else {
                CommonUtil.showAlert("错误", "客户信息更新失败！", Alert.AlertType.ERROR);
            }
        });
        
        buttonBox.getChildren().addAll(cancelButton, saveButton);
        
        // 将所有组件添加到主容器
        mainContainer.getChildren().addAll(titleLabel, formGrid, buttonBox);
        
        // 创建滚动面板
        ScrollPane scrollPane = new ScrollPane(mainContainer);
        scrollPane.setFitToWidth(true);
        scrollPane.setFitToHeight(true);
        
        Scene scene = new Scene(scrollPane, 1300, 1000);
        scene.getStylesheets().add(getClass().getResource("/css/form.css").toExternalForm());
        
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    /**
     * 显示客户编辑页面
     * @param customerId 客户ID
     */
    public static void showEditCustomer(int customerId) {
        CustomerService service = new CustomerService();
        Customer customer = service.getCustomerById(customerId);
        
        if (customer != null) {
            EditCustomerPage editPage = new EditCustomerPage(customer);
            try {
                editPage.start(new Stage());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            CommonUtil.showAlert("错误", "未找到客户信息！", Alert.AlertType.ERROR);
        }
    }
} 